﻿using itemApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace itemApi.Controllers
{
    public class roleController : ApiController
    {
        [HttpGet]
        public IHttpActionResult getroletable(string rname,int page,int limit)
        {
            using (crmEntities db = new crmEntities())
            {
                var list = db.Roles.AsEnumerable();
                if (!string.IsNullOrEmpty(rname)) {

                    list = list.Where(x => x.rname.Contains(rname));
                }
                

                var thelist = list.Select(x => new
                {
                    rid = x.rid,
                    rname = x.rname

                }).ToList();
                var count = thelist.Count();
                return Json(new { count = count, data = thelist.OrderByDescending(x => x.rid).Skip((page - 1) * limit).Take(limit) });
            }
        }
        //新增角色
        public IHttpActionResult addrole([FromBody] Roles ro) {
            using (crmEntities db = new crmEntities()) {
                string name = ro.rname;
                var thename = db.Roles.FirstOrDefault(x => x.rname == ro.rname);
                if (thename == null)
                {
                    db.Roles.Add(ro);
                    int n = db.SaveChanges();
                    if (n > 0)
                    {
                        return Json(new { code = 0, msg = "新增成功" });
                    }
                    else
                    {
                        return Json(new { code = -1, msg = "新增失败" });
                    }
                }
                else {
                    return Json(new { code = -1, msg = "该用户已经存在，请重新输入角色" });
                }
            }
        }

        public IHttpActionResult editrole([FromBody] Roles ro) {
            using (crmEntities db = new crmEntities()) {
                var therole = db.Roles.FirstOrDefault(x => x.rid == ro.rid);
                therole.rname = ro.rname;
                int n = db.SaveChanges();
                if (n > 0)
                {
                    return Json(new { code = 0, msg = "编辑成功" });
                }
                else {
                    return Json(new { code = -1, msg = "编辑失败" });
                }

            }


        }

        // 删除角色
        public IHttpActionResult del([FromBody] Roles ro)
        {
            using (crmEntities db = new crmEntities())
            {
                var therole = db.Roles.FirstOrDefault(x => x.rid == ro.rid);
                var therolemodules = db.RoleModules.Where(x => x.RoleId == ro.rid).ToList();
                var thruserrole = db.UserRoles.Where(x => x.RoleId == ro.rid).ToList();
                if (therolemodules != null) {
                    foreach (var item in therolemodules) {
                        db.RoleModules.Remove(item);
                    }
                    db.SaveChanges();

                }
                if (thruserrole != null) {
                    foreach (var item in thruserrole) {
                        db.UserRoles.Remove(item);
                    }
                    db.SaveChanges();
                }
                db.Roles.Remove(therole);
                int n = db.SaveChanges();
                if (n > 0)
                {
                    return Json(new { code = 0, msg = "删除成功" });
                }
                else
                {
                    return Json(new { code = -1, msg = "删除失败" });
                }

            }


        }

        //获取角色模块树形列表
        [HttpGet]
        public IHttpActionResult getroletree(int rid)
        {
            using (crmEntities db = new crmEntities())
            {
                var AuthorizeInfo = db.Modules.Where(p => true);
                var tempdata = from a in AuthorizeInfo
                               where a.ParentId == 0
                               select new
                               {
                                   Id = a.Id,
                                   Name = a.Name,
                                   ParentId = a.ParentId,
                                   Path = a.Path,
                                   Weight = a.Weight,
                                   children = from t in AuthorizeInfo
                                              where t.ParentId == a.Id
                                              select new
                                              {
                                                  Id = t.Id,
                                                  Name = t.Name,
                                                  ParentId = t.ParentId,
                                                  Path = t.Path,
                                                  Weight = t.Weight
                                              }
                               };
                //通过rid获取选中的角色模块
                List<int> mouduleid = new List<int>();
                var rolesid = db.RoleModules.Where(x => x.RoleId == rid).ToList();
                var roleid = rolesid.Select(x => new
                {
                    mouduleid = x.ModuleId
                }).ToList();
                foreach (var item in roleid) {
                    mouduleid.Add(Convert.ToInt32(item.mouduleid));
                }

                return Json(new { data = tempdata.ToList(),data2=mouduleid });
            }
        }
        //更新角色模块
        public IHttpActionResult editrolemoudule([FromBody]Roles ro) {
            using (crmEntities db = new crmEntities()) {
                var userridlist = db.RoleModules.Where(p =>p.RoleId==ro.userid).ToList();
                if (ro.str == "" || ro.str == null)
                {
                    foreach (var item in userridlist)
                    {
                        db.RoleModules.Remove(item);
                    }
                    db.SaveChanges();
                    return Json(new { code = -1, msg = "请先选择模块" });
                }
                List<int> mid = new List<int>();
                var splitid = ro.str.Split(',').ToList();
                foreach (var item in splitid) {
                    mid.Add(Convert.ToInt32(item));
                }
            
                foreach (var item in userridlist) {
                    db.RoleModules.Remove(item);
                }
                db.SaveChanges();
                foreach (var item in mid) {
                    RoleModules the = new RoleModules() { RoleId = ro.userid, ModuleId = item };
                    db.RoleModules.Add(the);

                }
              int n=db.SaveChanges();
                if (n > 0)
                {
                    return Json(new { code = 0, msg = "修改成功" });

                }
                else {
                    return Json(new { code = -1, msg = "修改失败" });
                }

               
               

            }


        }
    }
    }

